<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\StudyLocationModel;
use App\Models\KeywordMappingModel;
use App\Models\PageLinksModel;
use App\Models\FeatureStatusModel;

class Yanxue extends Controller
{
    public function set_keyword()
    {
        $featureStatusModel = new FeatureStatusModel();
        $canEditKeywords = $featureStatusModel->where('feature_key', "can_edit_keywords")->first();
        $editKeywordStatus = $canEditKeywords["status"];

        if (0 == $editKeywordStatus) {
            return redirect()->back()->with('error', '关键词功能关闭');
        }

        $keyword = $this->request->getPost('keyword');
        $page_id = $this->request->getPost('page_id');

        // 验证关键词长度
        if (mb_strlen($keyword) === 2) {
            $data = [
                'keyword' => $keyword,
                'page_id' => $page_id,
                'readonly' => 0,
            ];

            // 创建 KeywordMappingModel 实例
            $keywordMappingModel = new KeywordMappingModel();

            try {
                // 检查是否已存在相同的关键词和页面ID组合
                $existingRecord = $keywordMappingModel->where([
                    'keyword' => $keyword,
                    'page_id' => $page_id
                ])->first();

                if ($existingRecord) {
                    return redirect()->back()->with('error', '该关键词已存在于此页面');
                }

                // 使用模型插入数据
                $insertId = $keywordMappingModel->insert($data);

                if ($insertId) {
                    return redirect()->back()->with('message', '关键词添加成功');
                } else {
                    // 获取模型的错误信息
                    $errors = $keywordMappingModel->errors();
                    return redirect()->back()->with('error', '数据插入失败: '. implode(', ', $errors));
                }
            } catch (\Exception $e) {
                // 捕获异常并返回错误信息
                return redirect()->back()->with('error', '数据插入失败: '. $e->getMessage());
            }
        } else {
            return redirect()->back()->with('error', '关键词长度必须为2个字'.$keyword.mb_strlen($keyword));
        }
    }

    public function remove_keyword()
    {
        
        $featureStatusModel = new FeatureStatusModel();
        $canEditKeywords = $featureStatusModel->where('feature_key', "can_edit_keywords")->first();
        $editKeywordStatus = $canEditKeywords["status"];

        if (0 == $editKeywordStatus) {
            return redirect()->back()->with('error', '关键词功能关闭');
        }

        $request = \Config\Services::request();
        $keyword = $request->getPost('keyword');
        $page_id = $request->getPost('page_id');

        // 实例化 KeywordMappingModel
        $keywordMappingModel = new KeywordMappingModel();

        // 调用模型方法删除关键词记录
        $result = $keywordMappingModel->where('keyword', $keyword)
                                      ->where('page_id', $page_id)
                                      ->delete();

        if ($result) {
            $this->session->setFlashdata('message', '关键词删除成功');
        } else {
            $this->session->setFlashdata('error', '关键词删除失败');
        }

        return redirect()->back();
    }

    public function set_link()
    {
        $featureStatusModel = new FeatureStatusModel();
        $canEditLinks = $featureStatusModel->where('feature_key', "can_edit_links")->first();
        $editLinkStatus = $canEditLinks["status"];

        if (0 == $editLinkStatus) {
            return redirect()->back()->with('error', '推荐链接功能关闭');
        }

        $request = service('request');
        $link = $request->getPost('link');
        $linkTxt = $request->getPost('linkTxt');
        $fromPageId = $request->getPost('page_id');
        $toPageId = $request->getPost('toPageId');
        if ($toPageId === 0 || empty($linkTxt)) {
            return redirect()->back()->with('error', '目标页面 ID 无效或链接文本为空');
        }
        // 加载 PageLinksModel
        $linkModel = new PageLinksModel();

        // 准备要插入的数据
        $data = [
            'link_url' => $link,
            'link_txt' => $linkTxt,
            'from_page_id' => $fromPageId,
            'to_page_id' => $toPageId,
        ];
        log_message('info', "Received link data: link={$link}, linkTxt={$linkTxt}, fromPageId={$fromPageId}, toPageId={$toPageId}");

        try {
            $linkModel->db->transStart();
            // 检查是否已存在相同的链接记录（相同的 link_url, from_page_id 和 to_page_id）
            $existingRecord = $linkModel->where([
                'link_url' => $link,
                'from_page_id' => $fromPageId,
                'to_page_id' => $toPageId
            ])->first();

            if ($existingRecord) {
                session()->setFlashdata('error', '该链接已存在');
            } else {
                // 插入数据到数据库
                if ($linkModel->insert($data)) {
                    $this->updateToPageScore($fromPageId);
                    session()->setFlashdata('message', '链接添加成功');
                } else {
                    session()->setFlashdata('error', '链接添加失败');
                }
            }

            $linkModel->db->transComplete();

            if ($linkModel->db->transStatus() === false) {
                session()->setFlashdata('error', '数据库操作失败');
            }
        } catch (\Exception $e) {
            log_message('error', "Database operation failed: ". $e->getMessage());
            session()->setFlashdata('error', '数据库操作失败: '. $e->getMessage());
        }

        return redirect()->back();
    }

    public function remove_link()
    {
        $featureStatusModel = new FeatureStatusModel();
        $canEditLinks = $featureStatusModel->where('feature_key', "can_edit_links")->first();
        $editLinkStatus = $canEditLinks["status"];

        if (0 == $editLinkStatus) {
            return redirect()->back()->with('error', '推荐链接功能关闭');
        }

        $request = service('request');
        $toPageId = $request->getPost('toPageId');
        $fromPageId = $request->getPost('fromPageId');

        // 加载 PageLinksModel
        $linkModel = new PageLinksModel();

        $result = $linkModel->where('to_page_id', $toPageId)
                                      ->where('from_page_id', $fromPageId)
                                      ->delete();

        if ($result) {
            $this->updateToPageScore($fromPageId);
            session()->setFlashdata('message', '链接删除成功');
        } else {
            session()->setFlashdata('error', '链接删除失败');
        }

        return redirect()->back();
    }

    public function updateToPageScore($fromPageId)
    {
        // 加载 PageLinksModel
        $linkModel = new PageLinksModel();

        $results = $linkModel->where('from_page_id', $fromPageId)->findAll();
        $count = count($results);
        $score = ($count > 0) ? 1 / $count : 0;
        // log_message('info', "开始更新分值，fromPageId: {$fromPageId}, score: {$score}, 记录数: {$count}");
        // 提取 study_location_id
        foreach ($results as $page_link) {
        	$sql = "UPDATE page_links SET score = ? WHERE id = ?";
			$result = $linkModel->db->query($sql, [$score, $page_link['id']]);
            $sql = $linkModel->db->getLastQuery();
        }

    }
}